package com.whnk.web.controller.pm;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.whnk.common.annotation.Log;
import com.whnk.common.base.AjaxResult;
import com.whnk.common.config.Global;
import com.whnk.common.enums.BusinessType;
import com.whnk.framework.web.base.BaseController;
import com.whnk.framework.web.page.TableDataInfo;
import com.whnk.pm.domain.IncomePro;
import com.whnk.pm.dto.IncImpErrorDto;
import com.whnk.pm.service.IIncomeProService;
import com.whnk.pm.util.ValidateException;

/**
 * 月度收入报送（按项目） 信息操作处理
 * 
 * @author whwhnk
 * @date 2022-09-06
 */
@Controller
@RequestMapping("/pm/incomePro")
public class IncomeProController extends BaseController
{
    private String prefix = "pm/incomePro";
	
	@Autowired
	private IIncomeProService incomeProService;
	
	@RequiresPermissions("pm:incomePro:view")
	@GetMapping()
	public String incomePro()
	{
	    return prefix + "/incomePro";
	}
	
	/**
	 * 查询月度收入报送（按项目）列表
	 */
	@RequiresPermissions("pm:incomePro:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(IncomePro incomePro)
	{
		startPage();
        List<IncomePro> list = incomeProService.selectIncomeProList(incomePro);
		return getDataTable(list);
	}
	
	/**
	 * 新增月度收入报送（按项目）
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存月度收入报送（按项目）
	 */
	@RequiresPermissions("pm:incomePro:add")
	@Log(title = "月度收入报送（按项目）", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(IncomePro incomePro)
	{		
		return toAjax(incomeProService.insertIncomePro(incomePro));
	}

	/**
	 * 修改月度收入报送（按项目）
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		IncomePro incomePro = incomeProService.selectIncomeProById(id);
		mmap.put("incomePro", incomePro);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存月度收入报送（按项目）
	 */
	@RequiresPermissions("pm:incomePro:edit")
	@Log(title = "月度收入报送（按项目）", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(IncomePro incomePro)
	{		
		return toAjax(incomeProService.updateIncomePro(incomePro));
	}
	
	/**
	 * 删除月度收入报送（按项目）
	 */
	@RequiresPermissions("pm:incomePro:remove")
	@Log(title = "月度收入报送（按项目）", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(incomeProService.deleteIncomeProByIds(ids));
	}
	
	/**
	 * 根据报送年月和项目名称计算报送统计表
	 * 
	 * @param wlYm  报送年月
	 * @param proName 项目名称
	 * @return
	 */
	@Log(title = "收入报送单", businessType = BusinessType.OTHER)
	@PostMapping("/countBywlYm")
	@ResponseBody
    public AjaxResult countByWlYm(String wlYm, String proName) {
		incomeProService.countByWlYm(wlYm, proName);
		return success();
	}
	
	/**
	 * 下载月度收入数据模板
	 * 
	 * @return
	 */
	@PostMapping("/template")
    @ResponseBody
    public AjaxResult downloadTemplate(){
    	  try {
			InputStream stream =BaseInfoController.class.getResourceAsStream("/MonIncomeModel.xlsx");
			File downloadFile = new File(Global.getDownloadPath() + File.separator + "MonIncomeModel.xlsx");
			
			FileUtils.copyToFile(stream, downloadFile);

			String filename = downloadFile.getName();
			String result = URLEncoder.encode(filename, "UTF-8");
			return AjaxResult.success(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	 return AjaxResult.error("下载失败");
    }
	
	/**
	 * 导入月度收入数据EXCEL
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@Log(title = "Excel导入月度收入数据", businessType = BusinessType.UPDATE)
	@PostMapping("/impExcel")
	@ResponseBody
	public AjaxResult empInfoImport(@RequestParam("excelFile") MultipartFile file) throws Exception {
		try {
			if (!file.isEmpty()) {
				String uploadFileName = file.getOriginalFilename();
				
				// 基本检查......
				// int size = (int) file.getSize();
				// Boolean flag = false;
				
				// 保存文件
				File desc = getAbsoluteFile(Global.getProfile(), uploadFileName);
				file.transferTo(desc);
				List<IncImpErrorDto> msg = new ArrayList<IncImpErrorDto>();
				try {
					incomeProService.impExcel(desc.getAbsolutePath(), msg);
				} catch (Throwable throwable) {
					if (throwable instanceof ValidateException) {
						if (msg.size() == 0) {
							return success();
						} else {
							StringBuffer buffer = new StringBuffer();
							for (IncImpErrorDto errorDto : msg) {
								buffer.append(errorDto.toString()).append("<br>");
							}
							return error(buffer.toString());
						}
					} else {
						return error("导入失败");
					}
				}
				return success();
			}
			return error();
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}
	
	private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {
		File desc = new File(uploadDir + File.separator + "upload" + File.separator + filename);
		if (!desc.getParentFile().exists()) 
			desc.getParentFile().mkdirs();
		if (!desc.exists()) 
			desc.createNewFile();
		return desc;
	}

}
